(function() {
	
	if (!window.CJ) {
		window.CJ = {};
	}


	function Episode () {
		this.name = 'Episode';
		this.rootID = '#info';
		this.rootElem = $(this.rootID+" .scroll>ul");
		this.moveDistance = -50;
		this.pageUnitCount = 6;
		this.area = "list"; /* back , list, info */
		this.bindEvent();
	}

	Episode.totalCount = 0;
	Episode.pageSize = 50;
	Episode.pageNo = 0;
	Episode.lists = [];
	Episode.setID = function (id) {
		this.lastID = id;
	};
	Episode.isDataLoading = false;
	Episode.getData = function (pID, succCB) {
		if (Episode.isDataLoading ) {
			console.log('Episode data loading....');
			return;
		}
		Episode.isDataLoading = true;
		var programID = pID || CJ.Program.lastID;
		if (pID) {
			this.lists = [];
			this.totalCount = 0;
			this.pageNo = 0;
			CJ.Program.setID(programID);
			$( CJ.Scene["Episode"].rootID ).css('opacity', 0);
			CJ.Scene["Episode"].rootElem.html('');
			CJ.Scene["EpisodeSub"].rootElem.html('');
			//$(this.rootID).hide();
		}
		CJ.HttpJson.get({
			type: 'EPISODELIST',
			param: {
				programid: programID,
				pageSize: this.pageSize,
				pageNo: this.pageNo + 1
			},
			success:  function (json) {
				$( CJ.Scene["Episode"].rootID ).css('opacity', 1);
				Episode.successCB(json);
				//진입시에만
				if(pID) {
					CJ.Scene["Episode"].renderDetail();
				}
				if (typeof succCB == 'function') {
					succCB();
				}
			},
			complete: function () {
				Episode.isDataLoading = false;
			}
		});
	};
	Episode.getMore = function (pID) {
		if (this.totalPage != this.pageNo) {
			this.getData();
		}
	};
	Episode.successCB = function (json) {
		this.lists = this.lists.concat(json.episodelist);
		this.totalCount = parseInt(json.total_count);
		this.totalPage =  parseInt(json.page_info.total_page);
		this.pageNo =  parseInt(json.page_info.page);
		CJ.Scene["Episode"].render(json.episodelist);
		CJ.Scene["EpisodeSub"].render(json.episodelist);
	};

	Episode.prototype = new CJ.Vertical();
	Episode.prototype.bindEvent = function () {
		var self = this;
		$(this.rootID+ " .scrollbar>.up").on('click', function(){
			self.pageUp();
		});
		$(this.rootID+ " .scrollbar>.down").on('click', function(){
			self.pageDown();
		});
		$(this.rootElem).on('click', 'li', function(){
			self.clickList($(this));
		});
		$(this.rootID+ " .scrollbar>.up").on('click', 'li', function(){
			self.pageUp();
		});
		$(this.rootID+ " .scrollbar>.down").on('click', 'li', function(){
			self.pageDown();
		});
		
		
		/* 생성 전 객체에 이벤트 */
		//영화보기 버튼에 Click
		$(this.rootID).on('click',  '.box-info ul li', function(evt){
			self.viewVod();
		});
		//영화보기 버튼에 mouseover
		$(this.rootID).on('mouseenter', '.box-info ul li', function(evt){
			self.area = 'info';
			$('div.btn-back>.btn').removeClass('focus');
			$('li.focus', self.rootElem).removeClass('focus');
			$(this).addClass('focus');
		});
		
		//List에 mouseover
		$(this.rootElem).on('mouseenter', 'li', function(evt){
			self.area = 'list';
			$('div.btn-back>.btn').removeClass('focus');
			$('li.focus', self.rootElem).removeClass('focus');
			$(self.rootID + ' .box-info li').removeClass('focus');
			$(this).addClass('focus');
		}).on('mouseleave', 'li', function(evt){
			$(this).removeClass('focus');
			$('li.select', self.rootElem).addClass('focus');
		});
	};
	Episode.prototype.changeEvent = function () {
		var self = this;
		$('div.btn-back>.btn').off('click').on('click', function() {
			CJ.Scene.program();
		});
		//back 버튼에 mouseover
		$('div.btn-back>.btn').off('mouseenter').on('mouseenter', function(evt){
			self.area = 'back';
			$('div.btn-back>.btn').addClass('focus');
			$('li.focus',  self.rootElem).removeClass('focus');
			$(self.rootID + ' .box-info li').removeClass('focus');
		});
	};
	
	Episode.prototype.render = function (lists) {
		var childCount = this.rootElem.children().length;
		var method =  childCount > 0 ? 'append' : 'html';
		$( this.rootElem )[method](
			$.render.episodeTemplate( lists )
		);
		if (method == 'html') {
			var initIndex = lists.length > 1 ? 1 : 0;
			var topPX = parseInt(initIndex * this.moveDistance) + 'px';
			$("#wrap").hasClass(this.rootID.replace('#',''));

			$(this.rootID+'>h2').html('<img src="img/tit_'+ CJ.Channel.lastID+'.png" alt=""><br>' + lists[initIndex].programtitle);
			var s = $( this.rootElem ).css({top: topPX}).children('li:nth-child('+parseInt(initIndex+1)+')').addClass('select');
			if ($("#wrap").hasClass(this.rootID.replace('#',''))) {
				s.addClass('focus');
			}
		}
		var ulH = $( this.rootElem ).height();
		var scrollCount = Math.round(ulH / 300);
		var scrollBarHeight = Math.floor(210 / scrollCount);
		$(this.rootID+ " .scrollbar>div.bar").height(scrollBarHeight);
	};
	Episode.prototype.renderDetail = function () {
		var idx = $("li.select", this.rootElem).index();
		if (this.preIndex != idx) {
			this.preIndex = idx;
			$(this.rootID+' .box-info').html(
				$.render.episodeDetailTemplate( Episode.lists[idx] )
			)
			this.scrollDesc();
		}
	};
	Episode.prototype.extend = function () {
		Episode.getMore();
		this.renderDetail();
		this.scrollBarMove();
	};
	Episode.prototype.setFocus = function (eID) {
		var initIndex = $( 'li[data-episodeid="'+eID+'"]', this.rootElem ).index();
		var topPX = parseInt(initIndex * this.moveDistance) + 'px';
		$( this.rootElem ).css({top: topPX}).children('li:nth-child('+parseInt(initIndex+1)+')').addClass('select focus').siblings().removeClass('select focus');
	};
	Episode.prototype.scrollBarMove = function () {
		var self = this;
		var idx = $("li.select", this.rootElem).index();
		var pos = Math.floor(idx/6);
		var ulH = $( this.rootElem ).height();
		var scrollCount = Math.round(ulH / 300);
		var scrollBarHeight = Math.floor(210 / scrollCount);
		var scrollBarTop = pos*scrollBarHeight + 45;
		if (scrollBarTop < 210) {
			// $(self.rootID+ " .scrollbar>div.bar").addClass('focus');
			// setTimeout(function(){
				// $(self.rootID+ " .scrollbar>div.bar").removeClass('focus');
			// }, 300);
			$(this.rootID+ " .scrollbar>div.bar").css({
				height: scrollBarHeight,
				top: (pos*scrollBarHeight + 45)+'px',
			});
		}
	};
	Episode.prototype.scrollDesc = function () {
		this.stopScrollDesc();
		var moveH =0,
			wrapH = 85;
		var desc = $('#desc_info');
		var descH = $('#desc_info').height();
		var scrollH = descH - wrapH;
		if (scrollH > 0) {
			this.timer = setInterval(function(){
				moveH = moveH - 15;
				if (scrollH + moveH < 0) {
					moveH = 0;
				}
				desc.css({top: moveH +'px'});
			}, 1000);
		}
	};
	Episode.prototype.stopScrollDesc = function () {
		clearInterval(this.timer);
		$('#desc_info').css({top: '0px'});
	};
	Episode.prototype.left = function () {
		if (this.area == "info") {
			this.area = "list";
			$(this.rootID+ ">.box-info li").removeClass('focus');
			$("li.select", this.rootElem).addClass('focus');
		} else if (this.area == "list") {
			this.area = "back";
			$("li", this.rootElem).removeClass('focus');
			$('div.btn-back>.btn').addClass('focus');
		} else {
			this.back();
		}
	};
	Episode.prototype.right = function () {
		if (this.area == "list") {
			this.area = "info";
			$('li.select', this.rootElem).removeClass('focus');
			$(this.rootID+' .box-info li').addClass('focus');
		} else if (this.area == "back") {
			this.area = "list";
			$("li.select", this.rootElem).addClass('focus');
			$('div.btn-back>.btn').removeClass('focus');
		}
	};
	Episode.prototype.back = function () {
		$('div.btn-back>.btn').removeClass('focus');
		this.stopScrollDesc();
		CJ.Scene.program();
	};
	Episode.prototype.enter = function () {
		//리스트 클릭
		if (this.area == "list") {
			this.clickList();
		// 영상보기 클릭
		} else if (this.area == "info"){
			this.viewVod()
		} else if (this.area == "back"){
			this.back()
		}
	};
	Episode.prototype.clickList = function (elem) {
		if (typeof elem == 'undefined') {
			var now = $("li.select", this.rootElem);
			var idx = now.index();
			this.renderDetail();
			this.area = "info";
			now.removeClass('focus');
			$(this.rootID+' .box-info li').addClass('focus');
		} else {
			$("li", this.rootElem).removeClass('select focus');
			elem.addClass('select focus');
			this.renderDetail();
		}
	};
	Episode.prototype.viewVod = function () {
		//컨텐츠 선택
		this.stopScrollDesc();
		var now = $("li.select", this.rootElem);
		var idx = now.index();
		var pid = CJ.Program.lastID;
		var eid = now.data('episodeid');
		var price = now.data('price');
		var grade = now.data('grade');
		//과금 체크 및 과금 후 재생 요청
		function vaildUser () { //과금유저
			VideoPlay(idx, pid, eid);
		}
		function invalidUser () {//미과금유저
			CJ.Scene.billing(pid, eid, price, vaildUser);
		}
		CJ.plugin.billing.checkBilling( pid, eid,
							vaildUser,
							invalidUser,
							grade);
	};
	CJ.Episode = Episode;


	function EpisodeSub () {
		this.name = 'EpisodeSub';
		this.template = 'episodeSubTemplate';
		this.rootID = '#vod div.list .dep3';
		this.did = 'data-episodeid';
		this.rootElem = $(this.rootID+" ol");
		this.bindEvent();
	}
	EpisodeSub.prototype = new CJ.SubList();
	EpisodeSub.prototype.enter = function (evt) {
		this.extend();
		var now = $(this.rootID + ' .focus');
		if (now.hasClass('btn_prev')){
			CJ.Horizon.prototype.pageUp.call(this);
		} else if (now.hasClass('select')) {
			//컨텐츠 선택
			var idx = now.index();
			var pid = CJ.Program.lastID;
			var eid = now.data('episodeid');
			var price = now.data('price');
			var grade = now.data('grade');
			//과금 체크 및 과금 후 재생 요청
			function vaildUser () { //과금유저
				VideoPlay(idx, pid, eid, true);
			}
			function invalidUser () { //미과금유저
				CJ.Scene.billing(pid, eid, price, vaildUser);
			}
			//자동감춤 멈춤
			CJ.AutoHideCtl.stop();
			CJ.plugin.billing.checkBilling( pid, eid,
								vaildUser,
								invalidUser,
								grade);
		} else if (now.hasClass('btn_next')){
			CJ.Horizon.prototype.pageDown.call(this);
		}
	};
	CJ.EpisodeSub = EpisodeSub;

	function VideoPlay (idx, pid, eid, isSub) { //과금유저
		$('#vod>h3>span').text(Episode.lists[idx].episodetitle + ' - ' + CJ.util.getDateStr( Episode.lists[idx].broaddate, '/'));
		$('#vod>h3 .num').text(Episode.lists[idx].likecount);
		CJ.Video.play(pid, eid, CJ.Scene.episode);
		Episode.setID(eid);
		if (isSub) CJ.Scene["Episode"].setFocus(eid);
	}

	
	$.extend(CJ.Scene, {
							episode: function(){
								var self = this;
								CJ.AutoHideCtl.stop();
								this["Episode"].area = "list";
								this["Episode"].changeEvent();
								$(this["Program"].rootID + " li.focus").removeClass('focus');
								$(this["Episode"].rootID + " li.select").addClass('focus');
								$(this["Episode"].rootID + " .box-info li").removeClass('focus');
								$("#wrap").removeClass().addClass(this["Episode"].rootID.replace('#',''));
								this.setDelegate(this["Episode"]);
							}
						});

	$(document).ready(function(){
		CJ.Scene["Episode"] = new CJ.Episode();
		CJ.Scene["EpisodeSub"] = new CJ.EpisodeSub();
	});
})();